package pactera.tf.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import pactera.tf.dataobj.LoginDO;
import pactera.tf.excpetion.R;
import pactera.tf.excpetion.ResultCodeEnum;
import pactera.tf.service.LoginService;
import pactera.tf.service.RedisService;

import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    LoginService loginService;

    @Autowired
    private RedisService redisService;

    @GetMapping("/")
    public String tologin(){
        return "user/login";
    }
    /**
     * 登陆
     * */
    @PostMapping("/justlogin")
    @ResponseBody
    public R login(@RequestBody LoginDO login, HttpSession session){
        Map<String, Object> hashMap = loginService.checkLogin(login);
        LoginDO loginDO = (LoginDO)hashMap.get("logininfo");
        R r = (R)hashMap.get("R");
        if(ResultCodeEnum.SUCCESS.getCode().equals(r.getCode())){
            //设置登录状态到redis
            redisService.set("onlin-user"+loginDO.getUserid(),"Y");

        }else{
            return r;
        }
        session.setAttribute("userid",loginDO.getUserid());
        return R.ok().message("登录成功");
    }

    /**
     * 注册接口
     */
    @PostMapping(value="/register",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R register(@RequestBody LoginDO loginDO){

        boolean registerRet = loginService.register(loginDO);
        R result = null ;
        if(registerRet){
            return  R.ok().message("用户注册成功");

        }else{
            return R.error().message("用户已存在");
        }
    }
    @RequestMapping("/toRegister")
    public String toRegister(){
        return "user/register";
    }

    /**
     * 清session
     */
    @RequestMapping("/chat/clearSessionInfo")
    @ResponseBody
    public void register(HttpServletRequest request){

        Object userid = request.getSession().getAttribute("userid");
        if(userid != null){
            request.getSession().removeAttribute("userid");
            redisService.delete("onlin-user"+userid);
        }
    }
}
